// memory_usage.cpp

#include <string>
#include <sstream>
#include <iostream>
// 1）确定操作系统
#if defined(_WIN32) || defined(_WIN64)
    #define PLATFORM_WINDOWS
#elif defined(__linux__)
    #define PLATFORM_LINUX
#elif defined(__APPLE__) && defined(__MACH__)
    #define PLATFORM_MAC
#else
    #error "Platform not supported!"
#endif

// 2）编写平台特定的内存信息获取代码

#ifdef PLATFORM_WINDOWS
    #include <windows.h>

    std::string getMemoryUsage() {
        MEMORYSTATUSEX statex;
        statex.dwLength = sizeof(statex);
        if (!GlobalMemoryStatusEx(&statex)) {
            return "Failed to get memory status.";
        }
        std::ostringstream stream;
        stream << "Total physical memory: " << statex.ullTotalPhys / (1024 * 1024) << " MB, "
               << "Available physical memory: " << statex.ullAvailPhys / (1024 * 1024) << " MB";
        return stream.str();
    }
#endif

#ifdef PLATFORM_LINUX
    #include <fstream>

    std::string getMemoryUsage() {
        std::ifstream file("/proc/meminfo");
        if (!file.is_open()) {
            return "Failed to open /proc/meminfo.";
        }

        std::string line;
        std::ostringstream stream;
        while (std::getline(file, line)) {
            stream << line << '\n';
            if (line.find("MemAvailable:") == 0) {
                break;
            }
        }
        file.close();
        return stream.str();
    }
#endif

#ifdef PLATFORM_MAC
    #include <sys/types.h>
    #include <sys/sysctl.h>

    std::string getMemoryUsage() {
        int mib[2];
        int64_t physical_memory;
        size_t length = sizeof(physical_memory);

        // 设置mib以获取物理内存大小
        mib[0] = CTL_HW;
        mib[1] = HW_MEMSIZE;
        if (sysctl(mib, 2, &physical_memory, &length, NULL, 0) != 0) {
            return "Failed to get memory status.";
        }

        std::ostringstream stream;
        stream << "Total physical memory: " << physical_memory / (1024 * 1024) << " MB";
        return stream.str();
    }
#endif

// 3）提供统一的接口
std::string getMemoryUsage();

int main() {
    std::string memoryInfo = getMemoryUsage();
    // 输出内存信息
    // 这里可以根据需要选择输出方式，例如打印到控制台
    #ifdef PLATFORM_WINDOWS
        MessageBoxA(NULL, memoryInfo.c_str(), "Memory Usage", MB_OK);
    #else
        std::cout << memoryInfo << std::endl;
    #endif
    return 0;
}
